import * as vscode from 'vscode';

export class TextHelper {
  private static readonly DEFAULT_TRUNCATE_LENGTH = 100;

  // 截断文本，避免输出过长
  static truncate(text: string, maxLength: number = this.DEFAULT_TRUNCATE_LENGTH): string {
    if (!text || text.length <= maxLength) return text;
    
    // 尝试在合适的位置截断（空格、换行等）
    const truncated = text.slice(0, maxLength);
    const lastSpace = truncated.lastIndexOf(' ');
    const lastNewline = truncated.lastIndexOf('\n');
    
    const cutPoint = Math.max(lastSpace, lastNewline);
    if (cutPoint > maxLength * 0.7) { // 如果截断点不会损失太多内容
      return truncated.slice(0, cutPoint) + '...';
    }
    
    return truncated + '...';
  }

  // 获取指定行的文本
  static getLineText(doc: vscode.TextDocument, line: number): string {
    if (line < 0 || line >= doc.lineCount) return '';
    return doc.lineAt(line).text;
  }

  // 获取代码上下文
  static getCodeContext(doc: vscode.TextDocument, errorLine: number, contextLines: number = 2): string[] {
    const context: string[] = [];
    const startLine = Math.max(0, errorLine - contextLines);
    const endLine = Math.min(doc.lineCount - 1, errorLine + contextLines);

    for (let i = startLine; i <= endLine; i++) {
      const lineText = this.getLineText(doc, i);
      const marker = i === errorLine ? ' --> ' : '     ';
      context.push(`${marker}${i + 1}: ${lineText}`);
    }

    return context;
  }

  // 计算字符串相似度
  static calculateSimilarity(str1: string, str2: string): number {
    const longer = str1.length > str2.length ? str1 : str2;
    const shorter = str1.length > str2.length ? str2 : str1;

    if (longer.length === 0) return 1.0;

    const editDistance = this.getEditDistance(longer, shorter);
    return (longer.length - editDistance) / longer.length;
  }

  // 计算编辑距离
  private static getEditDistance(str1: string, str2: string): number {
    const matrix = [];

    for (let i = 0; i <= str2.length; i++) {
      matrix[i] = [i];
    }

    for (let j = 0; j <= str1.length; j++) {
      matrix[0][j] = j;
    }

    for (let i = 1; i <= str2.length; i++) {
      for (let j = 1; j <= str1.length; j++) {
        if (str2.charAt(i - 1) === str1.charAt(j - 1)) {
          matrix[i][j] = matrix[i - 1][j - 1];
        } else {
          matrix[i][j] = Math.min(
            matrix[i - 1][j - 1] + 1,
            matrix[i][j - 1] + 1,
            matrix[i - 1][j] + 1
          );
        }
      }
    }

    return matrix[str2.length][str1.length];
  }

  // 清理和格式化文本
  static cleanText(text: string): string {
    return text
      .replace(/\r\n/g, '\n')  // 统一换行符
      .replace(/\t/g, '  ')    // 制表符转空格
      .trim();
  }

  // 检查文本是否包含有用信息
  static hasUsefulContent(text: string): boolean {
    if (!text || text.trim().length === 0) return false;
    
    // 过滤掉一些无用的内容
    const uselessPatterns = [
      /^[\s\-_.]*$/,           // 只包含空白字符和分隔符
      /^unknown$/i,            // 只是"unknown"
      /^error$/i,              // 只是"error"
    ];

    return !uselessPatterns.some(pattern => pattern.test(text.trim()));
  }
}